package com.example.exchangeapp.pxx;

import android.os.Bundle;
import android.os.NetworkOnMainThreadException;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;

import com.example.exchangeapp.R;
import com.example.exchangeapp.yy.constant.AppId;
import com.example.exchangeapp.yy.constant.AppSecret;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class RecordsActivity extends AppCompatActivity {

    private ListView listView;
    private ImageButton serchBtn;
    private List<Record> records;
    private RecordsAdapter recordsAdapter;
    private androidx.appcompat.widget.Toolbar toolbar;
    private String id;
    private SearchView searchView;
    private String keyword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_records);

        Bundle bundle=getIntent().getExtras();
        id=bundle.getString("id");

        listView=findViewById(R.id.records_list);
        toolbar=findViewById(R.id.records_toolbar);
        serchBtn=findViewById(R.id.serchBtn);
        searchView = findViewById(R.id.search_view);
        setSupportActionBar(toolbar);

        serchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                searchView.setVisibility(View.VISIBLE);
            }
        });

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                keyword=query;
                refreshData(1);
                // 处理搜索逻辑
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
//                keyword=newText;
//                refreshData(1);
                return false;
            }
        });
        initData();
    }

    private void initData() {
        records = new ArrayList<>();
        recordsAdapter = new RecordsAdapter(RecordsActivity.this,
                R.layout.list_item, records);
        listView.setAdapter(recordsAdapter);
        refreshData(1);
    }

    private void refreshData(final int page) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                // url路径
                String url = "http://47.107.52.7:88/member/tran/trading/records?size=100&userId=";
                // 请求头
                Headers headers = new Headers.Builder()
                        .add("Accept", "application/json, text/plain, */*")
                        .add("appId", AppId.AppId)
                        .add("appSecret", AppSecret.appSecret)
                        .build();
                String pram=id+"&keyword="+keyword;
                if(keyword==null){
                    url=url+id;
                    Log.i("RecordsActivity",url);
                }else{
                    url=url+pram;
                    Log.i("RecordsActivity",url);
                }
                //请求组合创建
                Request request = new Request.Builder()
                        .url(url)
                        // 将请求头加至请求中
                        .headers(headers)
                        .get()
                        .build();
                try {
                    OkHttpClient client = new OkHttpClient();
                    //发起请求，传入callback进行回调
                    client.newCall(request).enqueue(callback);
                }catch (NetworkOnMainThreadException ex){
                    ex.printStackTrace();
                }
            }
        }).start();
    }

    private okhttp3.Callback callback = new okhttp3.Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response)
                throws IOException {
            System.out.println("res"+response.toString());
            if (response.isSuccessful()) {
                final String body = response.body().string();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Gson gson = new Gson();
                        BaseResponse baseResponse =
                                gson.fromJson(body, BaseResponse.class);
                        if(baseResponse.getData()==null){
                            recordsAdapter.clear();
                            recordsAdapter.notifyDataSetChanged();
                            Toast.makeText(RecordsActivity.this, "没有相关记录！", Toast.LENGTH_SHORT).show();
                        }else{
                            recordsAdapter.clear();
                            for(int i=0;i<baseResponse.getData().getTotal();i++){
                                Record record=baseResponse.getData().getRecords().get(i);
                                recordsAdapter.add(record);
                            }
                            recordsAdapter.notifyDataSetChanged();
                            Toast.makeText(RecordsActivity.this, "搜索成功！", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            } else {
            }
        }
    };

}